/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package postersender;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Berk
 */
public class Sender extends Thread {

    private DBHandler db;
    private InetAddress CheckerAdress;
    private int port;

    public Sender(DBHandler dataBase) {
        InputStream is = null;
        this.db = dataBase;
        try {
            this.CheckerAdress = InetAddress.getByName(Constants.CheckerAddress);
            this.port = Constants.Port;
        } catch (IOException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                ResultSet rs = db.getUnsentFlags();
                if (rs.first()) {
                    while (rs.next()) {
                        String flag = rs.getString("flag");
                        db.changeStatus(flag, send(flag));
                    }
                }
                Thread.sleep(20000);
            }
        } catch (InterruptedException | SQLException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String send(String flag) {
        String reply="";
        try {
            Socket sck = new Socket(this.CheckerAdress, this.port);
            DataInputStream inps = new DataInputStream(sck.getInputStream());
            DataOutputStream outs = new DataOutputStream(sck.getOutputStream());
            outs.writeChars(flag);
            outs.flush();
            reply = inps.readUTF();
                    
        } catch (IOException ex) {
            Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
        }
        return reply;
    }
}
